﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using Entities;
using Logic;
using VotanetWebSite.Classes;
using WebLog;

namespace VotanetWebSite
{
    public partial class Login_Votante : System.Web.UI.Page
    {
        private readonly string KEY = ConfigurationManager.AppSettings["KEY"].ToString();
        private readonly string USER_MAIL = ConfigurationManager.AppSettings["USER"].ToString();
        private readonly string USER_PASSWORD = ConfigurationManager.AppSettings["PASSWORD"].ToString();
        private readonly string MAIL_SERVER = ConfigurationManager.AppSettings["MAIL_SERVER_NAME"].ToString();
        private readonly string PATHCAPTCHA = HttpContext.Current.Server.MapPath("~/Images/CaptchaImages/");
        private List<string> imagesCaptchaList = new List<string>();
        private Captcha c = new Captcha();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsCookieEnabled())
            {
                Response.RedirectPermanent("Mensajes_Error/Cookies_Desactivadas.aspx");
                return;
            }
            if (!IsPostBack)
            {
                GenerateCaptcha();
            }

        }

        protected void BotonEnviar_Click(object sender, EventArgs e)
        {
            Page.Validate();
            if (Page.IsValid)
            {
                Login();
            }
            else
            {
                Response.RedirectPermanent("Mensajes_Error/JavaScript_Desactivado.aspx");
            }

        }

        protected bool IsCookieEnabled()
        {
            string url = Request.RawUrl;
            if (Request.QueryString["ComprobarCookie"] == null)
            {
                try
                {
                    HttpCookie c = new HttpCookie("CompruebaCookie", "true");
                    Response.Cookies.Add(c);
                    if (url.IndexOf("?") > 0)
                    {
                        url = url + "&ComprobarCookie=true";
                    }
                    else
                    {
                        url = url + "?ComprobarCookie=true";
                    }
                    Response.Redirect(url);
                }
                catch (Exception ex)
                {
                    //pico
                    //var p = e;
                }
            }

            if (!Request.Browser.Cookies || Request.Cookies["CompruebaCookie"] == null)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        protected void ImageCaptchaReload_Click(object sender, ImageClickEventArgs e)
        {
            txtCaptcha.Text = string.Empty;
            GenerateCaptcha();
        }

        private void DeleteCaptcha()
        {
            try
            {
                foreach (string str in imagesCaptchaList)
                {
                    File.Delete(str);
                }
            }
            catch (Exception e)
            {
                //pico...
                Logger logger = Logger.GetInstance;
                logger.WriteLog(e);
            }

            imagesCaptchaList.Clear();
        }

        protected void Login()
        {
            FormsAuthentication.Initialize();

            VoterLogic voterLogic = new VoterLogic();
            string ip = GetIpAddress();
            string browser = Request.Browser.Browser;
            Voter voter = voterLogic.GetVoterLogic(txtrut.Text, txtContrasena.Text, ip, browser, KEY, GetPathGeoDataBase());

            if (voterLogic.ValidateCaptcha(txtCaptcha.Text, Session["captchacode"] as string))
            {

                if (voter != null)
                {
                    if (voter.blocked == false)
                    {
                        voterLogic.SendEmailLogic(voter, "Ha iniciado actividad en nuestro sistema", USER_MAIL, USER_PASSWORD, MAIL_SERVER, null);
                        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, voter.rut, DateTime.Now, DateTime.Now.AddMinutes(10), false, "votante", FormsAuthentication.FormsCookieName);
                        string encryptCookie = FormsAuthentication.Encrypt(ticket);
                        HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptCookie);
                        Response.Cookies.Add(cookie);
                        Session["Voter"] = voter;
                        DeleteCaptcha();
                        Response.RedirectPermanent("~/Home/Pagina_Inicio.aspx");
                    }
                    else
                    {
                        CleanForm();
                        Messages.Show(Page, Messages.BLOCKED_USER);
                    }
                }
                else
                {
                    CleanForm();
                    Messages.Show(Page, Messages.VOTER_NOT_EXIT);

                }
            }
            else
            {
                Messages.Show(Page, Messages.INVALID_CAPTCHA);
                GenerateCaptcha();

            }


        }

        protected string GetIpAddress()
        {
            string ip = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (string.IsNullOrWhiteSpace(ip))
            {
                ip = Request.ServerVariables["REMOTE_ADDR"];
                if (string.IsNullOrWhiteSpace(ip))
                {
                    ip = "";
                }
            }

            return ip;
        }

        public string GetPathGeoDataBase()
        {
            string databasePath = string.Empty;
            try
            {
                databasePath = HttpContext.Current.Server.MapPath("~/app_data/GeoLiteCity.dat");
            }
            catch (Exception e)
            {
                Logger logger = Logger.GetInstance;
                logger.WriteLog(e);
                databasePath = null;
            }
            return databasePath;
        }

        private void GenerateCaptcha()
        {
            c.Generate(140, 40);
            string code = c.GetCode();
            string imageCaptchaPath = c.SaveImage(PATHCAPTCHA, code);
            imagesCaptchaList.Add(PATHCAPTCHA + imageCaptchaPath);
            Session["captchacode"] = code;

            ImageCaptcha.ImageUrl = "~/Images/CaptchaImages/" + imageCaptchaPath;
        }

        protected void CleanForm()
        {
            txtrut.Text = string.Empty;
            txtContrasena.Text = string.Empty;
            //txtContrasena2.Text = string.Empty;
        }
    }
}